<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>服务管理</el-breadcrumb-item>
      <el-breadcrumb-item>底图服务</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="filterName" @input="inputAlter" placeholder="底图名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleUpload()">
          上传服务集
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="
      dataList.slice(
        (this.pageparm.currentPage - 1) * this.pageparm.pageSize,
        this.pageparm.currentPage * this.pageparm.pageSize
      )
    " highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%">
      <el-table-column sortable prop="name" label="底图名称"> </el-table-column>
      <el-table-column sortable prop="dataType" label="底图类型"> </el-table-column>
      <el-table-column prop="id" label="底图ID"> </el-table-column>
      <el-table-column prop="url" label="服务地址"> </el-table-column>
      <el-table-column sortable prop="created_at" label="创建时间">
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="deleteRow(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 上传对话框 -->
    <el-dialog title="上传服务集" :visible.sync="uploadDialogVisible" width="30%" @close="closeUploadDialog">
      <div class="container">
        <el-upload class="upload" drag :action="upurl" :headers="headers" :before-upload="beforeUpload"
          :on-success="afterTilesUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将服务集数据文件(.mbtiles)拖到此处，或<em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            只能上传栅格瓦片数据集，支持xyz规范的mbtiles底图库
          </div>
        </el-upload>
      </div>
    </el-dialog>
    <!-- 编辑界面 -->
    <el-dialog title="编辑底图信息" :visible.sync="editDialogVisible" width="30%" @close="closeEditDialog">
      <el-form label-width="120px" :model="editRow" ref="editRow">
        <el-form-item label="底图名称">
          <el-input size="small" v-model="editRow.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="底图类型" prop="type">
          <el-select v-model="editRow.type" placeholder="请选择">
            <el-option v-for="item in oltypes" :key="item.label" :label="item.label" :value="item.label" disabled>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitEdit('editRow')">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from "../../components/Pagination";

  export default {
    data() {
      return {
        loading: false, //是显示加载
        uploadDialogVisible: false,
        editDialogVisible: false, //控制编辑页面显示与隐藏
        filterName: "", //搜索框内容
        upurl: cfg.baseURL + "/olmaps/upload/",
        headers: {
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
        editRow: {
          id: "",
          name: "",
          type: ""
        },
        oltypes: [
          {
            label: "离线底图",
          },
          {
            label: "在线底图",
          },
        ],
        // rules表单验证
        rules: {
          id: [{ required: true, message: "底图id不能为空", trigger: "blur" }],
          name: [{ required: true, message: "请输入底图名称", trigger: "blur" }],
          type: [{ required: true, message: "请选择底图类型", trigger: "blur" }],
        },
        dataList: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10,
        },
        thumbnail:
          "",
      };
    },
    // 注册组件
    components: {
      Pagination,
    },
    /**
     * 创建完毕
     */
    created() {
      // 获取底图列表
      this.getDataList();
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // 获取底图列表
      getDataList() {
        this.$axios.get("/olmaps/").then((res) => {
          this.dataList = res.data.results;
          this.pageparm.total = res.data.results.length;
        });
      },
      // 分页插件事件
      callFather(parm) {
        this.pageparm.currentPage = parm.currentPage;
        this.pageparm.pageSize = parm.pageSize;
      },
      handleUpload() {
        this.uploadDialogVisible = true;
      },
      beforeUpload(file) {
        let lext = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
        const isMbtiles = lext === ".mbtiles";

        if (!isMbtiles) {
          this.$message.error("上传数据只能是 .mbtiles 格式!");
        }

        return isMbtiles;
      },

      afterTilesUpload(res, file) {
        console.log("upload res,", res);
        this.$axios
          .post("/olmaps/info/" + res.results.id + "/", {
            thumbnail: this.thumbnail,
          })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            this.$message.error("更新默认缩略图失败，请稍后再试！");
          });
      },

      //显示编辑界面
      handleEdit: function (index, row) {
        this.editDialogVisible = true;
        this.editRow.id = row.id;
        this.editRow.name = row.name;
        this.editRow.type = row.type;
      },
      // 编辑、增加页面保存方法
      submitEdit(editData) {
        this.$refs[editData].validate((valid) => {
          if (valid) {
            this.loading = true;
            this.$axios
              .post("/olmaps/info/" + this.editRow.id + "/", {
                name: this.editRow.name,
                type: this.editRow.type,
              })
              .then((res) => {
                this.editDialogVisible = false;
                this.loading = false;
                this.getDataList();
              })
              .catch((err) => {
                this.editDialogVisible = false;
                this.loading = false;
                this.$message.error("编辑数据提交失败，请稍后再试！");
              });
          }
        });
      },
      // 删除
      deleteRow(index, row) {
        console.log("🚀 ~ file: service.vue ~ line 206 ~ deleteRow ~ row", row)
        console.log("🚀 ~ file: service.vue ~ line 206 ~ deleteRow ~ index", index)
        this.$confirm("确定要删除吗?", "信息", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then((res) => {

            this.$axios.post("/olmaps/delete/" + row.id + "/").then((res) => {
              this.getDataList();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      closeUploadDialog() {
        this.uploadDialogVisible = false;
        this.getDataList();
      },
      // 关闭编辑、增加弹出框
      closeEditDialog() {
        this.editDialogVisible = false;
      },

      // 输入框内容改变
      inputAlter() {
        if (this.filterName == "") {
          this.getDataList();
        } else {
          this.dataList = this.dataList.filter((value) => {
            return value.name.match(this.filterName);
          });
          this.pageparm.total = this.dataList.length;
        }
      },
      // 搜索事件
      search() {
        this.dataList = this.dataList.filter((value) => {
          return value.name.match(this.filterName);
        });
        this.pageparm.total = this.dataList.length;
      },
    },
  };
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }

  .el-upload-list--picture .el-upload-list__item-thumbnail {
    display: none !important;
  }

  .container {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  .upload {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
</style>